<template>
    <div class="sms-test-container">
        <div class="test-card">
            <h2>短信功能测试页面</h2>
            <p>用于测试改进后的短信验证码功能和消息显示</p>
            
            <div class="test-section">
                <h3>📱 发送短信验证码测试</h3>
                <div class="input-group">
                    <el-input
                        v-model="testPhone"
                        placeholder="请输入测试手机号"
                        maxlength="11"
                        style="width: 200px; margin-right: 10px;"
                    />
                    <el-button
                        type="primary"
                        @click="testSendSms"
                        :disabled="smsCountdown > 0"
                    >
                        {{ smsCountdown > 0 ? `${smsCountdown}s后重发` : '发送验证码' }}
                    </el-button>
                </div>
                <div class="tips">
                    <p><strong>测试说明：</strong></p>
                    <ul>
                        <li>验证码不在前端显示，请查看后端控制台或Redis</li>
                        <li>60秒内不能重复发送</li>
                        <li>验证码有效期5分钟</li>
                        <li>后端控制台会输出JSON格式的验证码信息</li>
                    </ul>
                </div>
            </div>
            
            <div class="test-section">
                <h3>🔍 查询验证码状态测试</h3>
                <div class="input-group">
                    <el-input
                        v-model="queryPhone"
                        placeholder="请输入要查询的手机号"
                        maxlength="11"
                        style="width: 200px; margin-right: 10px;"
                    />
                    <el-button
                        type="info"
                        @click="testQueryStatus"
                    >
                        查询状态
                    </el-button>
                </div>
            </div>
            
            <div class="test-section">
                <h3>🔐 短信登录测试</h3>
                <div class="input-group">
                    <el-input
                        v-model="loginPhone"
                        placeholder="手机号"
                        maxlength="11"
                        style="width: 150px; margin-right: 10px;"
                    />
                    <el-input
                        v-model="loginCode"
                        placeholder="验证码"
                        maxlength="6"
                        style="width: 120px; margin-right: 10px;"
                    />
                    <el-button
                        type="success"
                        @click="testSmsLogin"
                    >
                        短信登录
                    </el-button>
                </div>
            </div>
            
            <div class="test-section">
                <h3>📊 测试结果显示</h3>
                <div class="result-area">
                    <div v-if="lastResponse" class="response-display">
                        <h4>最后一次API响应：</h4>
                        <pre>{{ JSON.stringify(lastResponse, null, 2) }}</pre>
                    </div>
                    <div v-else class="no-response">
                        暂无测试结果
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const testPhone = ref('13900139006')
const queryPhone = ref('13900139006')
const loginPhone = ref('13900139006')
const loginCode = ref('')
const smsCountdown = ref(0)
const lastResponse = ref(null)

// 发送短信验证码测试
async function testSendSms() {
    if (!testPhone.value || testPhone.value.length !== 11) {
        ElMessage.error('请输入正确的11位手机号')
        return
    }
    
    try {
        const response = await request.post('/sms/send', {
            phone: testPhone.value
        })
        
        lastResponse.value = response.data
        
                 const data = response.data
         if (data && data.code === 0) {
             // 统一显示发送成功消息，不显示验证码
             ElMessage({
                 message: `✅ ${data.msg}，验证码有效期5分钟（请查看后端控制台获取验证码）`,
                 type: 'success',
                 duration: 6000,
                 showClose: true
             })
            
            // 开始倒计时
            smsCountdown.value = 60
            const timer = setInterval(() => {
                smsCountdown.value--
                if (smsCountdown.value <= 0) {
                    clearInterval(timer)
                }
            }, 1000)
        }
    } catch (error) {
        if (error.response && error.response.data) {
            lastResponse.value = error.response.data
            const errorData = error.response.data
            
            if (errorData.msg && errorData.msg.includes('等待') && errorData.msg.includes('秒')) {
                ElMessage({
                    message: `⚠️ ${errorData.msg}`,
                    type: 'warning',
                    duration: 5000,
                    showClose: true
                })
            } else {
                ElMessage.error(`❌ ${errorData.msg || '发送失败'}`)
            }
        } else {
            ElMessage.error('❌ 网络错误，请稍后重试')
        }
    }
}

// 查询验证码状态测试
async function testQueryStatus() {
    if (!queryPhone.value || queryPhone.value.length !== 11) {
        ElMessage.error('请输入正确的11位手机号')
        return
    }
    
    try {
        const response = await request.post('/sms/status', {
            phone: queryPhone.value
        })
        
        lastResponse.value = response.data
        
        const data = response.data
        if (data && data.code === 0) {
            const statusInfo = data.data
            if (statusInfo.exists) {
                ElMessage({
                    message: `📋 验证码状态：有效 | 剩余时间：${statusInfo.remaining_time}秒 | 可重发：${statusInfo.can_resend ? '是' : '否'}`,
                    type: 'info',
                    duration: 6000,
                    showClose: true
                })
            } else {
                ElMessage({
                    message: '📋 验证码状态：不存在或已过期',
                    type: 'warning',
                    duration: 4000,
                    showClose: true
                })
            }
        }
    } catch (error) {
        if (error.response && error.response.data) {
            lastResponse.value = error.response.data
            ElMessage.error(`❌ ${error.response.data.msg || '查询失败'}`)
        } else {
            ElMessage.error('❌ 网络错误，请稍后重试')
        }
    }
}

// 短信登录测试
async function testSmsLogin() {
    if (!loginPhone.value || loginPhone.value.length !== 11) {
        ElMessage.error('请输入正确的11位手机号')
        return
    }
    
    if (!loginCode.value || loginCode.value.length !== 6) {
        ElMessage.error('请输入6位验证码')
        return
    }
    
    try {
        const response = await request.post('/sms/login', {
            phone: loginPhone.value,
            smsCode: loginCode.value
        })
        
        lastResponse.value = response.data
        
        const data = response.data
        if (data && data.code === 0) {
            const user = data.data?.user
            const welcomeMsg = user ? 
                `🎉 ${data.msg}！欢迎您，${user.nickname || user.username}` : 
                `🎉 ${data.msg}`
            
            ElMessage({
                message: welcomeMsg,
                type: 'success',
                duration: 5000,
                showClose: true
            })
        }
    } catch (error) {
        if (error.response && error.response.data) {
            lastResponse.value = error.response.data
            const errorData = error.response.data
            
            let errorMessage = errorData.msg || '登录失败'
            let messageType = 'error'
            
            if (errorData.msg.includes('验证码错误')) {
                errorMessage = '❌ 验证码输入错误，请重新输入'
                messageType = 'warning'
            } else if (errorData.msg.includes('已过期')) {
                errorMessage = '⏰ 验证码已过期，请重新获取验证码'
                messageType = 'warning'
            }
            
            ElMessage({
                message: errorMessage,
                type: messageType,
                duration: 5000,
                showClose: true
            })
        } else {
            ElMessage.error('❌ 网络错误，请稍后重试')
        }
    }
}
</script>

<style scoped>
.sms-test-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: flex-start;
}

.test-card {
    background: white;
    border-radius: 12px;
    padding: 30px;
    max-width: 800px;
    width: 100%;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.test-card h2 {
    color: #2c3e50;
    margin-bottom: 10px;
    text-align: center;
}

.test-card > p {
    color: #7f8c8d;
    text-align: center;
    margin-bottom: 30px;
}

.test-section {
    margin-bottom: 30px;
    padding: 20px;
    border: 1px solid #e1e8ed;
    border-radius: 8px;
    background: #fafbfc;
}

.test-section h3 {
    color: #34495e;
    margin-bottom: 15px;
    font-size: 16px;
}

.input-group {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.tips {
    margin-top: 15px;
    padding: 15px;
    background: #e8f4fd;
    border-left: 4px solid #409eff;
    border-radius: 4px;
}

.tips p {
    margin: 0 0 8px 0;
    font-weight: 600;
    color: #409eff;
}

.tips ul {
    margin: 0;
    padding-left: 20px;
}

.tips li {
    margin-bottom: 4px;
    color: #606266;
    font-size: 14px;
}

.result-area {
    max-height: 400px;
    overflow-y: auto;
}

.response-display h4 {
    color: #409eff;
    margin-bottom: 10px;
}

.response-display pre {
    background: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 15px;
    font-size: 12px;
    line-height: 1.5;
    overflow-x: auto;
    color: #2c3e50;
}

.no-response {
    text-align: center;
    color: #909399;
    padding: 40px 0;
    font-style: italic;
}

@media (max-width: 768px) {
    .input-group {
        flex-direction: column;
        align-items: stretch;
    }
    
    .input-group .el-input {
        width: 100% !important;
        margin-right: 0 !important;
        margin-bottom: 10px;
    }
}
</style> 